package factory

import (
    "fmt"
    "bookstore/store"
    "sync"
)

var (
    providersMu sync.RWMutex
    providers   = make(map[string]store.Store)
)

// Register 函数，让各个实现 Store 接口的类型可以把自己“注册”到工厂中来
func Register(name string, p store.Store)  {
    providersMu.Lock()
    defer providersMu.Unlock()
    if p == nil {
        panic("store: Register provider is nil")
    }

    if _, dup := providers[name]; dup {
        panic("store: Register called twice for provider " + name)
    }
    providers[name] = p
}

func New(providerName string) (store.Store, error)  {
    providersMu.RLock()
    p, ok := providers[providerName]
    providersMu.RUnlock()
    if !ok {
        return nil, fmt.Errorf("store: unknown porvider %s", providerName)
    }

    return p, nil
}
